import { unionModel, introduceModel, activityModel } from "./../model/unionModel";


export class _service {

    //新增 工会
    async createUnion(res: any) {
        //创建公会
        let result: any = await unionModel.create(res);
        //创建简介
        let result2: any = await introduceModel.create({ unionId: result._id, content: res.title + '简介' })
        return { code: 100, data: result, data2: result2 };
    }

    //获取工会列表
    async getUnionList() {
        let result: any = await unionModel.find().sort({ createDate: -1 });
        return { code: 100, data: result };
    }

    //根据工会主键 查询简介
    async getIntroduceById(res: any) {
        let result: any = await introduceModel.findOne({ unionId: res._id });
        return { code: 100, data: result };
    }

    //根据工会主键新增活动，默认为当前活动
    async createActivityById(res: any) {
        let _id: string = res.unionId;
        let findRes: any = await activityModel.find({ unionId: _id });
        if (findRes) {
            await activityModel.update({ unionId: _id }, { isHistory: 'yes' }, { upsert: false });
        }
        let result: any = await activityModel.create(res);
        return { code: 100, data: result };
    }

    //根据工会主键查询 活动 isHistory 
    async getActivityById(res: any) {
        let result: any = await activityModel.find(res).sort({ createDate: -1 });
        return { code: 100, data: result };
    }

    //根据工会主键 修改 简介
    async updateIntroduce(res: any) {
        let result: any = await introduceModel.update({ unionId: res.unionId }, res, { upsert: false });
        return { code: 100, data: result };
    }

    //测试用接口
    async testCreate(){
        /**
         * unionId: String,  //工会 主键
            content: [{ img: String, text: String }], //表体
            title: String,
            responsible: [{ userName: String, tel: String }],//负责人列表,
            setDate: String, //创立时间
            slogan: String //口号 标语
         */
        let find :any = await introduceModel.find();
        for (var i = 0; i < find.length; i++) {
            var element:any = find[i];
            
            for (var j = 0; j < element.content.length; j++) {
                var ele = element.content[j];
                if(j === 0 )
                    continue ;
                await activityModel.create({
                    unionId: element.unionId,  //工会 主键
                    title: '工会活动', //表体
                    responsible: element.responsible,//负责人列表,
                    activityDate: '2018-03-25',//活动时间
                    actImg: ele,
                    isHistory: 'no' //yes no
                })
            }
        }
    }
}

export default new _service();